<?php

namespace App\Controller\Api;

use App\Base\BaseController4Restful;
use App\Entity\OrderPackage;
use App\Entity\Orders;
use App\Entity\Task;
use App\Entity\TaskVote;
use App\Repository\TaskRepository;
use App\Repository\TaskVoteRepository;
use App\Service\MessageService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class ApiTaskVoteController extends BaseController4Restful
{
    /**
     * @Route("/api/taskVotes", name="apiGetTaskVotes",methods={"GET","POST"})
     */
    public function apiGetTaskVotes(TaskVoteRepository $repository,Request $request,TaskRepository $taskRepository,MessageService $messageService)
    {
        switch ($request->getMethod()) {
            case "POST":
                $user = $this->needToBeUser();
                $data = $this->getRequestData();
                $taskId = $data["task"];
                //检查任务状态
                $task = $taskRepository->find($taskId);
                if (!$task) {
                    return $this->json_out(400,"目标任务丢失");
                }
                if ($task->getStatus() >=300) {
                    return $this->json_out(400,"任务已关闭报价");
                }
                $this->myEm()->beginTransaction();
                try {
                    if ($task->getStatus() == 0) {
                        $task->setStatus(100);
                        $this->myEm()->persist($task);
                    }
                    $this->is->isTask($data["task"]);
                    $this->is->isFloat($data["price"]);
                    $this->is->isString($data["tips"]);
                    /**@var $TaskVote TaskVote*/
                    $TaskVote = $this->createEntity($data,TaskVote::class);
                    $TaskVote->setUser($user)->setCreateAt(new \DateTime())->setStatus(0);
                    $this->myEm()->persist($TaskVote);$this->myEm()->flush();
                    //报价后通知用户
                    $messageService->dealWithTaskVote($TaskVote);

                }catch (\Exception $exception){
                    $this->myEm()->rollback();
                    return $this->json_out(500,"系统繁忙");
                }
                $this->myEm()->commit();
                return $this->json_out(200,"提交成功", $TaskVote);
            default:
                if (!$page = $this->getParamRequired("page")) {$page = 1;}
                $limit = 10;
                $offset = (int)abs($limit * ($page - 1));
                $total = $repository->count([]);
                $this->setMeta($page,$total,$limit);
                $list = $repository->findBy(array(),array(),$limit,$offset);
                return $this->json_out(200,"获取成功", $list);
        }
    }

    /**
     * @Route("/api/taskVotes/{id}", name="apiAddTaskVotes",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiUpdateTaskVotes(TaskVote $TaskVote,Request $request)
    {
        $data = $this->getRequestData();
        switch ($request->getMethod()) {
            case "DELETE":
                $this->myEm()->remove($TaskVote);$this->myEm()->flush();
                return $this->json_out(200,"已移除");
            case "PATCH":
            case "PUT":
                /**@var $TaskVote TaskVote*/
                $TaskVote = $this->updateEntity($data,TaskVote::class,$TaskVote);
                break;
            case "Get":
            default:
        }
        $this->myEm()->persist($TaskVote);$this->myEm()->flush();
        return $this->json_out(200,"获取成功", $TaskVote);
    }

    /**
     * @Route("/api/task/{id}/votes", name="apiAddTaskVotesList",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiAddTaskVotesList(Task $task)
    {
        $data = $this->getRequestData();
        $votes = $task->getVote();

        $got = 0;
        $choosed = null ;
        foreach ($votes as $key => $vote) {
            if ($vote->getStatus() == 1) {
                $choosed = $vote;
                unset($votes[$key]);
            }
        }

        $data["choosed"] = $choosed;
        $data["votes"] = $votes;

        $this->setGroups("user","vote","home");
        return $this->json_out(200,"获取成功",$data);
    }

    /**
     * @Route("/api/task/hire/{id}", name="apiTaskVotesHire",methods={"GET","PUT","PATCH","POST"})
     */
    public function apiTaskVotesHire(TaskVote $taskVote)
    {
        $data = $this->getRequestData();
        $task = $taskVote->getTask();
        if ($task->getStatus() >= 300) {
            return $this->json_out(400,"已雇佣过其他用户");
        }
        $this->myEm()->beginTransaction();
        try {

            $task->setStatus(300);
            $taskVote->setStatus(1);
            $this->myEm()->persist($taskVote);

            //修改任务和投标的相关信息后创建一个订单
            $orders = new Orders();
            $orders->setBuyer($task->getUser())
                ->setSeller($taskVote->getUser())
                ->setAddress($task->getAddress())
                ->setContact($task->getContact())
                ->setSn($this->createOrderSn($task->getUser()->getId().$taskVote->getUser()->getId()))
                ->setCreateAt(new \DateTime())
                ->setPayTotal($taskVote->getPrice())
                ->setPayReal($taskVote->getPrice())
                ->setPaCode(md5($this->createOrderSn(rand())))
                ->setPayType(100)//todo 暂时不做支付
                ->setSales(null)//todo 暂时不做支付
                ->setPayAt(new \DateTime())
                ->setSettleAt(null)
                ->setSettleMessage(null)
                ->setType(1)
                ->setStatus(100)//todo 暂时不做支付
            ;
            $this->myEm()->persist($orders);
            $package = new OrderPackage();
            $package->setOrders($orders)
                ->setCreateAt(new \DateTime())
                ->setEntity($task)
                ->setNum(1)
                ->setPrice($taskVote->getPrice());
            $this->myEm()->persist($package);
            //绑定订单到任务
            $task->setOrders($orders);
            $this->myEm()->persist($task);

            $this->myEm()->flush();
        } catch (\Exception $e) {
            $this->myEm()->rollback();
            return $this->json_out(400,"系统繁忙，请稍后重试".$e->getMessage()."====".$e->getLine());
        }
        $this->myEm()->commit();
        return $this->json_out(200,"雇佣成功");
    }
}
